#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :page_1.py
# @Time      :2024/10/14 18:27
# @Author    :zhou_yi

from st_componets.my_st_comps import st_select_box_dic_opt, st_markdown_point_info, st_markdown_table_style, \
    st_markdown_clear_waster_record
import streamlit as st
import streamlit.components.v1 as components
from st_componets.st_fn import Fn

from st_componets.st_init import st_session_init

st_markdown_table_style()
st_session_init()  # 会话设置

"""  ----------------------页面-page1---------------------------   """
st.markdown('### 记录')
st.divider()

_Data = Fn.dfData()  # 读取数据信息转为dfData类实例
_Map = Fn.dfMap(width="1250px", height="780px")
_PointRecords = Fn.pointRecords()

# 判断数据库读取结果
if not _Data.customs:
    st.warning('数据库数据丢失....')
    st.stop()

with st.sidebar:
    with st.container(border=True):
        st.subheader("参数配置")

        custom = st.selectbox(label='客户名称', options=_Data.customs)

        names = st.multiselect(label='区域名称',
                               options=_Data.make_list_by_custom(custom)
                               )

        point_name = st.selectbox(label='点位名称',
                                  options=_Data.make_list_by_custom_and_names(custom, names)
                                  )

        c1, c2, c3 = st.columns([2, 2, 1])
        with c1:
            start_date = st.date_input(label='起始')
            st.session_state.start_date = start_date

        with c2:
            end_date = st.date_input(label='结束')
            st.session_state.end_date = end_date

        with c3:
            st.session_state.months = Fn.cac_months()
            st.number_input(label='总月数', value=st.session_state.months, disabled=True)

st.markdown("#### 有害垃圾清运记录")
tab1, tab2 = st.tabs(['地图坐标', '清运记录'])
with tab1:
    if names:
        _df = _Data.make_df_by_names(custom, names)  # 列表数据
        _date_pair = _Data.make_data_pair_by_name(names)  # 地图数据
    else:
        _df = _Data.make_df_by_custom(custom)  # 列表数据
        _date_pair = _Data.make_data_pair_by_custom([custom])  # 地图数据

    with st.expander(label='显示列表', expanded=False):
        st.dataframe(_df,
                     use_container_width=True,
                     hide_index=True)

    # 显示地图
    with st.expander(label='显示地图', expanded=False):
        _bm = _Map.show_points_on_map(data_pair=_date_pair)
        components.html(_bm.render_embed(), height=800)

# 点位记录显示
with tab2:
    if point_name:  # 已选点位
        # 求点位数据
        point_json = _Data.make_dict_by_point(point=point_name)

        # 生成点位数据对象
        pointRecs = (
            _PointRecords(start=start_date, end=end_date)
                .get_point_data(fn=_Data.make_dict_by_point, name=point_name)
                .really_records(fn=Fn.find_clear_waster_records_by_fk_and_date)
        )
        st.session_state.really_clear_records = pointRecs.to_word_tpl()

        # 侧边栏-- 生成文件
        with st.sidebar:
            with st.container(border=True):
                st.subheader("清运记录")
                # 提示
                st.code(f"""
                        生成
                        从{start_date.year}年{start_date.month}月至{end_date.year}年{end_date.month}月清运记录 
                        """)

                # 模版选择器
                current_tpl = st_select_box_dic_opt(label='应用模板', options=Fn.get_tpl_file(key="模板_记录"))

                # 下载真实记录文件
                Fn.download_clear_waster_record_docx_file(
                    tpl=current_tpl,  # 模板文件
                    context=st.session_state.really_clear_records,  # 模板数据 以函数的形式传递
                    point=(pointRecs.point_json['name'], pointRecs.point_json['_id']),  # 定义了下载到本地的文件名
                    key='生成真实记录'
                )

        # 中心区域
        c1, c2 = st.columns(2)
        with c1:  # 点位信息记录
            with st.container(border=True):
                st_markdown_point_info(data=point_json)  # 用html表格显示点位数据

        with c2:  # 点位清运记录

            with st.container():
                st.code(
                    f"""
                    该点位此时间段
                    共有 {len(pointRecs.records)} 条记录,缺少 {st.session_state.months - len(pointRecs.records)} 条记录
                    """)

                show = st.tabs(['真实数据', '伪造数据'])
                with show[0]:  # 渲染页面-真实数据
                    for r, s in zip(pointRecs.records, pointRecs.summary):
                        with st.expander(f'{s["idx"]}-记录 {r["datetime"]}-共清运：{s["w_total"]}公斤 /{s["is_really"]}'):
                            st_markdown_clear_waster_record(data=r)

                # 判断侧边栏是否显示随机记录
                if st.session_state.months > len(pointRecs.records):
                    # 侧边栏--随机记录
                    with st.sidebar:
                        with st.container(border=True):
                            st.subheader("随机记录")
                            # 提示
                            st.code(f"""
                                补充
                                从{start_date.year}年{start_date.month}月至{end_date.year}年{end_date.month}月随机记录 
                                """)
                            colD = st.columns(2)
                            with colD[0]:
                                btn_rnd_rec = st.button('随机创建', key='btn_rec')
                            with colD[1]:
                                btn_rnd_save = st.button('存储记录', key='btn_save')

                            # 下载伪造记录文件
                            Fn.download_clear_waster_record_docx_file(
                                tpl=current_tpl,  # 模板文件
                                context=st.session_state.rnd_clear_records,  # 模板数据 以函数的形式传递
                                point=(pointRecs.point_json['name'], pointRecs.point_json['_id']),  # 定义了下载到本地的文件名
                                key='生成伪造记录'
                            )

                    if btn_rnd_rec:
                        pointRecs.rnd_records_2()
                        st.session_state.rnd_clear_records = pointRecs.to_word_tpl()
                        with show[1]:  # 渲染页面-伪造数据
                            for r, s in zip(pointRecs.records, pointRecs.summary):
                                with st.expander(
                                        f'{s["idx"]}-记录 {r["datetime"]}-共清运：{s["w_total"]}公斤  /{s["is_really"]}'):
                                    st_markdown_clear_waster_record(data=r)

                    if btn_rnd_save:
                        # 批量插入数据库
                        Fn.insert_many_clear_waster_records(st.session_state.pointRecs.to_mongodb())
                        st.success('数据保存成功...')

                else:
                    with show[1]:
                        st.info('不需要提供伪造数据')

    else:
        st.info('选择一个点位名称')


